import 'package:flutter/material.dart';
import 'package:ycbl/config/bl_color.dart';
import 'package:ycbl/config/bl_style.dart';
import 'package:ycbl/utils/toast_util.dart';
import 'package:ycbl/view_model/send_code_view_model.dart';

import 'provider/bl_provider_widget.dart';

/// 发送验证码按钮
class SendCodeWidget extends StatelessWidget {

  /// 告诉我要获取验证码的手机号
  final String Function() getPhoneCallback;

  const SendCodeWidget({Key key, @required this.getPhoneCallback}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // provider 提供状态变化
    return BLProviderWidget<SendCodeViewModel>(
      notifierModel: SendCodeViewModel(),
      consumerBuilder: (context, model, child) {

        //请求接口中...
        if (model.isBusy || model.isPreCountdown) {
          return child; // holdChild 不变的 Widget
        }else {
          //非倒计时...
          if(model.isFinish) {
            return InkWell(
              child: Text('获取验证码', style: BLStyle.commonBlackTextStyle,),
              onTap: (){
                //获取手机号
                var phone = getPhoneCallback();
                //临时判断手机号，需要优化
                if (phone.isNotEmpty && phone.length == 11) {
                  //发送验证码
                  model.sendCode(phone, (isSuccess) {
                    ToastUtil.showShortToast(isSuccess ? '验证码已发送' : model.errorMessage ?? '获取验证码失败');
                  });
                }
              },
            );
          }else {
            //倒计时ing ...
            return Text(
              '${model.currTime}S后重新发送',
              style: BLStyle.commonBlackTextStyle.copyWith(color: BLColor.commonGreyTextColor,),
            );
          }
        }
      },
      holdChild: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text('获取中... ', style: BLStyle.commonBlackTextStyle.copyWith(color: BLColor.commonGreyTextColor,),),
          SizedBox(
            width: 16,
            height: 16,
            child: CircularProgressIndicator(
              // 背景色
              backgroundColor: Colors.grey.withAlpha(50),
              // 进度颜色
              valueColor: AlwaysStoppedAnimation(BLColor.commonGreyTextColor),
              // 线宽
              strokeWidth: 1.5,
            ),
          ),
        ],
      ),
    );
  }
}
